package com.example.mybatistest.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;

import java.util.*;

/**
 * 对于查询结果集（带下划线的字段)转换成驼峰模式
 */
@Slf4j
@Intercepts({
        @Signature(
                type = ResultHandler.class,
                method = "handleResult",
                args = {ResultContext.class}
        )
})
public class H_SqlHumpInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        List<Object>  result = (List<Object>) invocation.proceed();

        result.forEach(v -> {
            if (v instanceof Map) {
                processMap((Map<String, Object>)v);
            } else {
                return;
            }
        });
        return result;
    }



    void processMap(Map<String, Object> map) {
        Set<String> set = map.keySet();
        set.forEach(v-> {
            String newKey = convertHump(v);
            log.error("===> HH-HumpFormat: " + v + " -> " + newKey);
            map.put(newKey, map.get(v));
            map.remove(v);
        });
    }

    /**
     * 下划线转驼峰
     * @param f
     * @return
     */
    String convertHump(String f) {
        return Optional.ofNullable(f)
                .map(v -> {
                    StringBuffer sb = new StringBuffer();
                    Arrays.asList(v.toLowerCase().split("_"))
                            .stream()
                            .map(val -> Character.toUpperCase(val.charAt(0)) + val.substring(1))
                            .forEach(val -> {
                                sb.append(val);
                            });
                    return Character.toLowerCase(sb.toString().charAt(0)) + sb.toString().substring(1);
                })
                .orElse(f);

    }
}
